package com.jianyun.jyzs.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.OaAppBean;
import com.jianyun.jyzs.bean.TopBrodCastBean;
import com.jianyun.jyzs.utils.DensityUtil;
import com.jianyun.jyzs.view.custom.MyGridView;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by yangshijun on 2018/9/5.
 * <OaCustomAdapter.MyViewHodler>
 */

public class OaCustomAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<OaAppBean> oaBeanList;
    private OaMyGridAdapter oaMyGridAdapter;
    private int flowNum;
    private final int TOP_VIEWPAGER = 0;
    private final int CONTENT = 1;
    private int curIndex = 0;
    private String topBannerImgUrl;
    private ScheduledExecutorService scheduledExecutorService;
    ViewPager viewPager;
    LinearLayout dotgroup;
    private PicsAdapter picsAdapter;
    private Activity activity;
    private List<TopBrodCastBean.ImageList> imgList;
    private boolean isAddDotImg = false;

    //用来记录当前滚动的位置

    public OaCustomAdapter(Context context, List<OaAppBean> oaBeanList, Activity activity) {
        this.mContext = context;
        this.oaBeanList = oaBeanList;
        this.activity = activity;
    }

    public void setOaBeanList(List<OaAppBean> oaBeanList) {
        this.oaBeanList = oaBeanList;
        notifyDataSetChanged();
    }

    public void setBannerImg(String topBroadcast) {
        this.topBannerImgUrl = topBroadcast;
    }

    public void setTopBrodCast(List<TopBrodCastBean.ImageList> list){
        this.imgList=list;
        picsAdapter.setData(imgList);
        notifyDataSetChanged();
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TOP_VIEWPAGER;
        } else {
            return CONTENT;
        }
    }

    /**
     * 设置待办数字
     *
     * @param folowNum
     */
    public void setWorkFolowNum(int folowNum) {
        this.flowNum = folowNum;
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TOP_VIEWPAGER) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_oa_custom_top, parent, false);
            return new MyTopPagerHodler(view);
        } else {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_oa_custom, parent, false);
            return new MyViewHodler(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        int itemViewType = getItemViewType(position);

        if (itemViewType == TOP_VIEWPAGER) {
            setTopViewpager((MyTopPagerHodler) holder, position);
        } else {
            setOaCustomContent((MyViewHodler) holder, position);
        }

    }

    /**
     * 头部轮播图
     *
     * @param holder
     * @param position
     */

    private void setTopViewpager(MyTopPagerHodler holder, int position) {
        if (topBannerImgUrl == null || TextUtils.isEmpty(topBannerImgUrl)) {
            holder.viewPager.setVisibility(View.GONE);
            holder.dotgroup.setVisibility(View.GONE);
        } else {
            holder.viewPager.setVisibility(View.VISIBLE);
            holder.dotgroup.setVisibility(View.VISIBLE);
            if (viewPager == null) {
                viewPager = holder.viewPager;
                dotgroup = holder.dotgroup;
            }
            if (picsAdapter == null) {
                //图片轮播图
                // 创建适配器
                picsAdapter = new PicsAdapter(mContext);
                picsAdapter.setData(imgList);
                viewPager.setAdapter(picsAdapter); // 设置适配器
                viewPager.addOnPageChangeListener(new MyPageChangeListener());
                picsAdapter.setOnViewPagerClick(new PicsAdapter.OnViewPagerListener() {
                    @Override
                    public void onViewPagerClick(int positioin) {
                        onVpClickListener.onVpClick(positioin);
                    }
                });
            }
            if (!isAddDotImg&&imgList!=null) {
                initPoints(dotgroup, imgList.size()); // 初始化图片小圆点
                startAutoScroll(); // 开启自动播放
            }


        }

    }

    /**
     * 九宫格内容
     *
     * @param holder
     * @param position
     */
    private void setOaCustomContent(MyViewHodler holder, final int position) {
        holder.tvNode.setText(oaBeanList.get(position - 1).getAppName());
        oaMyGridAdapter = new OaMyGridAdapter(mContext, oaBeanList.get(position - 1).getItems());
        holder.myGridView.setAdapter(oaMyGridAdapter);
        oaMyGridAdapter.setWorkNum(flowNum);
        holder.myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int positions, long id) {
                onMyGridViewClickListener.onItemClick(position - 1, positions);
            }
        });
    }

    @Override
    public int getItemCount() {
        return oaBeanList == null ? 0 : oaBeanList.size() + 1;
    }

    class MyViewHodler extends RecyclerView.ViewHolder {

        TextView tvNode;
        MyGridView myGridView;

        public MyViewHodler(View itemView) {
            super(itemView);
            tvNode = itemView.findViewById(R.id.tv_node);
            myGridView = itemView.findViewById(R.id.my_grid_view);
        }
    }

    class MyTopPagerHodler extends RecyclerView.ViewHolder {

        ViewPager viewPager;
        LinearLayout dotgroup;

        public MyTopPagerHodler(View itemView) {
            super(itemView);
            viewPager = itemView.findViewById(R.id.view_page);
            dotgroup = itemView.findViewById(R.id.dotgroup);
        }
    }



    // 自动播放
    private void startAutoScroll() {
        scheduledExecutorService = Executors
                .newSingleThreadScheduledExecutor();
        // 每隔4秒钟切换一张图片
        ViewPagerTask pagerTask = new ViewPagerTask();
        scheduledExecutorService.scheduleWithFixedDelay(pagerTask, 5,
                4, TimeUnit.SECONDS);
    }

    // 切换图片任务
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int count = picsAdapter.getCount();
                    viewPager.setCurrentItem((curIndex + 1) % count);
                }
            });
        }
    }

    /**
     * @param count
     */
    // 初始化图片轮播的小圆点和目录
    private void initPoints(LinearLayout dotgroup, int count) {
        Log.i("test", "小圆点数目：" + count);
        int px = DensityUtil.dip2px(mContext, 7);
        for (int i = 0; i < count; i++) {
            ImageView iv = new ImageView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    px, px);
            params.setMargins(0, 0, px, 0);
            iv.setLayoutParams(params);
            iv.setImageResource(R.mipmap.dot2);

            dotgroup.addView(iv);
        }

        ((ImageView) dotgroup.getChildAt(curIndex))
                .setImageResource(R.mipmap.dot1);
        isAddDotImg = true;
    }


    // 定义ViewPager控件页面切换监听器
    class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            ImageView imageView1 = (ImageView) dotgroup.getChildAt(position);
            ImageView imageView2 = (ImageView) dotgroup.getChildAt(curIndex);
            if (imageView1 != null) {
                imageView1.setImageResource(R.mipmap.dot1);
            }
            if (imageView2 != null) {
                imageView2.setImageResource(R.mipmap.dot2);
            }
            curIndex = position;
        }

        boolean b = false;

        @Override
        public void onPageScrollStateChanged(int state) {
            //这段代码可不加，主要功能是实现切换到末尾后返回到第一张
            switch (state) {
                case 1:// 手势滑动
                    b = false;
                    break;
                case 2:// 界面切换中
                    b = true;
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter()
                            .getCount() - 1 && !b) {
                        viewPager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !b) {
                        viewPager.setCurrentItem(viewPager.getAdapter()
                                .getCount() - 1);
                    }
                    break;

                default:
                    break;
            }
        }
    }



    public interface OnMyGridViewClickListener {
        void onItemClick(int recyclerPostion, int myGridPositon);
    }

    private OnMyGridViewClickListener onMyGridViewClickListener;

    public void setMyGridClickListener(OnMyGridViewClickListener onMyGridViewClickListener) {
        this.onMyGridViewClickListener = onMyGridViewClickListener;
    }



    public interface OnVpClickListener{
        void onVpClick(int postion);
    }

    private OnVpClickListener onVpClickListener;

    public void setOnVpClickListener (OnVpClickListener onVpClickListener){
        this.onVpClickListener=onVpClickListener;
    }

}
